package cre.tomcat4.ch03.processor;

import cre.tomcat4.ch03.Constants;
import cre.tomcat4.ch03.connector.http.HttpRequest;
import cre.tomcat4.ch03.connector.http.HttpRequestFacade;
import cre.tomcat4.ch03.connector.http.HttpResponse;
import cre.tomcat4.ch03.connector.http.HttpResponseFacade;
import cre.tomcat4.util.LoaderUtils;

import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @Author penglai
 * @Date 2017/1/3.
 */
public class ServletProcessor {

    public void process(HttpRequest request, HttpResponse response) {
        String uri = request.getRequestURI();
        String servletName = gainServletName(uri);

        ClassLoader loader = gainLoader();
        Class sClass = null;
        try {
            sClass = loader.loadClass(Constants.SERVLET_CLASS_PACKAGE + servletName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Servlet servlet = null;
        try {
            servlet = (Servlet) sClass.newInstance();
            ServletRequest req = new HttpRequestFacade((HttpRequest) request);
            ServletResponse resp = new HttpResponseFacade(response);
            servlet.service(req, resp);
            response.finishResponse();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ClassLoader gainLoader() {
        return LoaderUtils.gainClassLoader();
    }

    private String gainServletName(String uri) {
        return uri.substring("/servlet".length() + 1);
    }
}
